import { stringify } from 'querystring';
import { history } from 'umi';
import { fakeAccountLogin, logout } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      // 发送请求执行登录
      const response = yield call(fakeAccountLogin, payload);
      console.log(response);

      // 判断是否登录成功
      if (response.status === undefined) {
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully

        // 跳转到首页
        history.replace('/');
      }

      // if (response.status === 'ok') {
      //   const urlParams = new URL(window.location.href);
      //   const params = getPageQuery();
      //   message.success('🎉 🎉 🎉  登录成功！');
      //   let { redirect } = params;

      //   if (redirect) {
      //     const redirectUrlParams = new URL(redirect);

      //     if (redirectUrlParams.origin === urlParams.origin) {
      //       redirect = redirect.substr(urlParams.origin.length);

      //       if (window.routerBase !== '/') {
      //         redirect = redirect.replace(window.routerBase, '/');
      //       }

      //       if (redirect.match(/^\/.*#/)) {
      //         redirect = redirect.substr(redirect.indexOf('#') + 1);
      //       }
      //     } else {
      //       window.location.href = '/';
      //       return;
      //     }
      //   }

      //   history.replace(redirect || '/');
      // }
    },

    // 退出登录 
    *logout(_, { call }) {

      // 请求Api，退出登录
      const response = yield call(logout)

      // 判断是否请求成功
      if (response.status === undefined) {
        // 删除本地存储的token和userInfo
        localStorage.removeItem('access_token')
        localStorage.removeItem('userInfo')

        // 重定向
        history.replace('/login')
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      // 将token存入localstorage
      localStorage.setItem("access_token", payload.access_token)
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
